
//音效
var correctAudio = wx.createInnerAudioContext();
var wrongAudio = wx.createInnerAudioContext();
correctAudio.src = 'pages/voice/right.mp3'; // 正确答案的音频文件路径
wrongAudio.src = 'pages/voice/wrong.mp3'; // 错误答案的音频文件路径

let A = 0;
let B = 0;
let op = "+";
Page({
    data: {
        timer: 30, // 默认倒计时时间
        questions: [], // 存储本场比赛的随机问题数组
        currentQuestionIndex: 0, // 当前题目索引
        userScore: 0, // 用户得分
        userAnswer: '', // 用户答案
        totalQuestions: 1024, // 本场比赛题数
        currentQuestion: '', // 当前问题内容
        questionType: ['+', '-', '*', '/'], // 可用的运算符
        countdownInterval: null // 存储倒计时的interval
        , wrongQuestions: [] // 错题集
    },

    onLoad: function () {
        let savedWrongQuestions = wx.getStorageSync('wrongQuestions') || []; //从本地存储获取错题集
        this.setData({
            wrongQuestions: savedWrongQuestions
        });
        this.generateQuestions(); // 生成随机题目
        this.startCompetition(); // 直接开始竞赛
    },

    generateQuestions: function () {
        const wrongQuestions = wx.getStorageSync('wrongQuestions') || [];
        const questions = [];
        for (let i = 0; i < this.data.totalQuestions; i++) {
            const question = this.generateRandomQuestion();
            questions.push(question);
        }
        this.setData({
            questions: questions,
            currentQuestion: questions[0].question, // 初始化当前问题
        });
    },

    generateRandomQuestion: function () {
        A = Math.floor(Math.random() * 10) + 1; // 1到10的随机数
        B = Math.floor(Math.random() * 10) + 1; // 1到10的随机数
        op = this.data.questionType[Math.floor(Math.random() * this.data.questionType.length)];

        let question = '';
        let answer;

        switch (op) {
            case '+':
                question = `${A} + ${B} = ?`;
                answer = A + B;
                break;
            case '-':
                question = `${A} - ${B} = ?`;
                answer = A - B;
                break;
            case '*':
                question = `${A} * ${B} = ?`;
                answer = A * B;
                break;
            case '/':
                // 避免除数为0，且让结果为整数
                const multiple = A * B;
                question = `${multiple} / ${B} = ?`;
                answer = multiple / B;
                break;
        }

        return {
            question: question,
            answer: answer,
            A: A,
            B: B,
            op: op,
        };
        // return { question, answer };
    },

    startCompetition: function () {
        this.setData({
            userScore: 0,
            opponentScore: 0,
            currentQuestionIndex: 0,
            timer: 30,
            userAnswer: '',
            currentQuestion: this.data.questions[0].question
        });
        this.startCountdown(); // 启动倒计时
        // this.loadNextQuestion(); // 加载第一题
    },

    loadNextQuestion: function () {
        const index = this.data.currentQuestionIndex;

        if (index < this.data.totalQuestions) {
            const nextQuestion = this.data.questions[index];
            this.setData({
                currentQuestion: nextQuestion.question,
                // timer: 30, // 重置计时器
                userAnswer: '', // 清空用户答案
            });

            // 启动倒计时
            this.startCountdown();
        } else {
            this.endCompetition(); // 结束比赛
        }
    },

    startCountdown: function () {
        // 清除之前的倒计时
        if (this.data.countdownInterval) {
            clearInterval(this.data.countdownInterval);
        }

        // 每秒更新倒计时
        const interval = setInterval(() => {
            if (this.data.timer > 0) {
                this.setData({ timer: this.data.timer - 1 });
            } else {
                clearInterval(interval);
                this.endCompetition(); // 时间到，结束比赛
            }
        }, 1000);

        this.setData({
            countdownInterval: interval
        });
    },

    endCompetition: function () {
        // 比赛结束时的逻辑，可以根据分数进行判断
        wx.showModal({
            title: '比赛结束',
            content: `你的得分: ${this.data.userScore}`,
            showCancel: false,
            success: (res) => {
                if (res.confirm) {
                    wx.navigateBack(); // 返回上一页或重新开始比赛
                }
            }
        });
    },

    onInput: function (e) {
        this.setData({
            userAnswer: e.detail.value
        });
    },

    submitAnswer: function () {
        const userAnswer = parseFloat(this.data.userAnswer);
        const currentQuestionObj = this.data.questions[this.data.currentQuestionIndex];
        const correctAnswer = currentQuestionObj.answer; // 当前题的正确答案
        if (userAnswer === correctAnswer) {
            this.setData({
                userScore: this.data.userScore + 1,
            });
            correctAudio.play();
        }
        else {
            wrongAudio.play();
            // 答错，将当前题目添加到错题集
            const wrongQuestions = wx.getStorageSync('wrongQuestions') || [];
            // const currentQuestion = this.data.questions[(this.data.currentQuestionIndex - 1) % this.data.totalQuestions];
            const currentQuestion = {
                A: currentQuestionObj.A,            // 数字 A
                B: currentQuestionObj.B,            // 数字 B
                op: currentQuestionObj.op,       // 运算符
                question: currentQuestionObj.question,   // 错题题目
                correctAns: correctAnswer,               // 正确答案
                userAns: userAnswer                      // 用户的错误答案
            };

            // 检查错题是否已存在
            const isAlreadyInWrongQuestions = wrongQuestions.some(question =>
                question.A === currentQuestion.A &&
                question.B === currentQuestion.B &&
                question.op === currentQuestion.op &&
                question.question === currentQuestion.question &&
                question.answer === currentQuestion.answer
            );

            if (!isAlreadyInWrongQuestions) {
                wrongQuestions.push(currentQuestion);
                wx.setStorageSync('wrongQuestions', wrongQuestions);
            }
        }

        // 清除倒计时
        clearInterval(this.data.countdownInterval);

        // 题目检查后，进入下一题
        this.setData({
            currentQuestionIndex: this.data.currentQuestionIndex + 1
        });

        // 立即加载下一题
        this.loadNextQuestion();
    },

    // 监听键盘事件
    onKeyPress: function (e) {
        if (e.keyCode === 13) { // 按回车键
            this.submitAnswer(); // 提交答案
        }
    },

    showWrongQuestions: function () {
        wx.navigateTo({
            url: '/pages/index/wrongQuestion'
        });
    }
});
